package controller

import (
	"hytx_manager/models"
	"hytx_manager/pkg/setting"
	"strconv"

	"github.com/Unknwon/com"
	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"
)

func AddPushMsg(c *gin.Context) {
	title := c.PostForm("title")
	icon := c.PostForm("icon")
	mtype := com.StrTo(c.PostForm("type")).MustInt()
	content := c.PostForm("content")
	link := c.PostForm("link")
	valid := validation.Validation{}
	valid.Required(title, "title").Message("标题不能为空")
	valid.Required(icon, "icon").Message("封面不能为空")
	valid.Required(mtype, "mtype").Message("类型不能为空")
	valid.Required(link, "link").Message("链接不能为空")
	valid.Max(mtype, 2, "mtype").Message("类型错误")

	if valid.HasErrors() || (mtype == 1 && len(content) == 0) {
		fail(c, "参数格式不对")
		return
	}

	data := make(map[string]interface{})
	data["title"] = title
	data["icon"] = icon
	data["type"] = mtype
	data["content"] = content
	data["link"] = link
	err := models.AddPushMsg(data)
	if err != nil {
		fail(c, err.Error())
		return
	}
	success(c)
}

func GetPushMsgs(c *gin.Context) {

	page := com.StrTo(c.DefaultQuery("page", "1")).MustInt()
	limit := com.StrTo(c.DefaultQuery("limit", strconv.Itoa(setting.AppSetting.PageSize))).MustInt()

	data, paginate := models.GetPushMsgs(page, limit)

	render(c, gin.H{
		"paginate": paginate,
		"data":     data,
	})

}
func GetPushMsg(c *gin.Context) {
	id := com.StrTo(c.Param("id")).MustInt()

	valid := validation.Validation{}
	valid.Min(id, 1, "id").Message("ID必须大于0")

	if valid.HasErrors() {
		fail(c, "参数格式不对")
		return
	}
	data := models.GetPushMsg(id)

	render(c, data)
}
func DeletePushMsg(c *gin.Context) {
	id := com.StrTo(c.Param("id")).MustInt()

	valid := validation.Validation{}
	valid.Min(id, 1, "id").Message("ID必须大于0")

	if valid.HasErrors() {
		fail(c, "参数格式不对")
		return
	}
	if !models.ExistPushMsgByID(id) {
		fail(c, "数据不存在")
		return
	}
	if !models.DeletePushMsg(id) {
		fail(c, "数据删除失败")
		return
	}
	success(c)
}
func EditPushMsg(c *gin.Context) {
	id := com.StrTo(c.Param("id")).MustInt()

	title := c.PostForm("title")
	icon := c.PostForm("icon")
	mtype := com.StrTo(c.PostForm("type")).MustInt()
	content := c.PostForm("content")
	link := c.PostForm("link")
	valid := validation.Validation{}
	valid.Required(title, "title").Message("标题不能为空")
	valid.Required(icon, "icon").Message("封面不能为空")
	valid.Required(mtype, "mtype").Message("类型不能为空")
	valid.Required(link, "link").Message("链接不能为空")
	valid.Max(mtype, 2, "mtype").Message("类型错误")

	if valid.HasErrors() || (mtype == 1 && len(content) == 0) {
		fail(c, "参数格式不对")
		return
	}
	if !models.ExistPushMsgByID(id) {
		fail(c, "数据不存在")
		return
	}
	data := make(map[string]interface{})
	if title != "" {
		data["title"] = title
	}
	if icon != "" {
		data["icon"] = icon
	}
	data["type"] = mtype
	if link != "" {
		data["link"] = link
	}
	if content != "" {
		data["content"] = content
	}

	if !models.EditPushMsgByID(id, data) {
		fail(c, "数据更改失败")
		return
	}
	success(c)
}
